package com.ruoyi.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.common.constant.RedisConstans;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.bean.BeanUtils;
import com.ruoyi.device.domain.ElectricFence;
import com.ruoyi.device.domain.ElectricFenceUser;
import com.ruoyi.device.domain.HatDevice;
import com.ruoyi.device.domain.req.fence.ElectricFenceAddReq;
import com.ruoyi.device.domain.req.fence.ElectricFenceEditReq;
import com.ruoyi.device.domain.req.fence.ElectricFenceReq;
import com.ruoyi.device.domain.req.hatdevice.HatDeviceAddReq;
import com.ruoyi.device.domain.resp.fence.ElectricFenceResp;
import com.ruoyi.device.service.ElectricFenceService;
import com.ruoyi.device.mapper.ElectricFenceMapper;
import com.ruoyi.device.service.ElectricFenceUserService;
import com.ruoyi.device.util.UpdateRedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
* @author 11452
* @description 针对表【electric_fence(电子围栏表)】的数据库操作Service实现
* @createDate 2023-12-02 11:47:09
*/
@Service
public class ElectricFenceServiceImpl extends ServiceImpl<ElectricFenceMapper, ElectricFence>
    implements ElectricFenceService{
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ElectricFenceUserService electricFenceUserService;

    @Autowired
    private UpdateRedisUtils updateRedisUtils;
    /**
     * 电子围栏查询*
     * @param req
     * @return
     */
    @Override
    public List<ElectricFenceResp> search(ElectricFenceReq req) {
        List<ElectricFenceResp> resp=this.baseMapper.search(req);
        return resp;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean add(ElectricFenceAddReq req) {
        //添加分布式锁 redis  setnx+过期时间(防止程序异常，做一个兜底收尾),加锁成功true,不成功false
       String redisKey= RedisConstans.ELECTRIC_FENCE_USER+req.getUserId();
        Boolean aBoolean = this.redisTemplate.opsForValue().setIfAbsent(redisKey, 1, 10, TimeUnit.SECONDS);
        if(aBoolean) {

            LambdaQueryWrapper<ElectricFence> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ElectricFence::getName, req.getName());
            queryWrapper.eq(ElectricFence::getDelFlag, "0");
            ElectricFence byName = getOne(queryWrapper);

            if (!Objects.isNull(byName)) {
                throw new ServiceException("电子围栏名称已存在");
            }

            LambdaQueryWrapper<ElectricFenceUser> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(ElectricFenceUser::getUserId, req.getUserId());

            ElectricFenceUser fenUser = this.electricFenceUserService.getOne(queryWrapper1);

            if (!Objects.isNull(fenUser)) {
                throw new ServiceException("该用户已经绑定了,创建电子围栏失败");
            }

            ElectricFence electricFence = new ElectricFence();
            BeanUtils.copyProperties(req, electricFence);

            electricFence.setDelFlag("0");

            boolean save = this.save(electricFence);
            //插入负责人
            ElectricFenceUser electricFenceUser = new ElectricFenceUser();
            electricFenceUser.setElectricId(electricFence.getId());
            electricFenceUser.setUserId(req.getUserId());
            electricFenceUser.setMobile(req.getMobile());
            this.electricFenceUserService.save(electricFenceUser);
            this.redisTemplate.delete(redisKey);
            return save;
        }else {
            throw new ServiceException("该用户已经绑定了,创建电子围栏失败");
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean edit(ElectricFenceEditReq req) {
        //添加分布式锁 redis  setnx+过期时间(防止程序异常，做一个兜底收尾),加锁成功true,不成功false
        String redisKey= RedisConstans.ELECTRIC_FENCE_USER+req.getUserId();
        Boolean aBoolean = this.redisTemplate.opsForValue().setIfAbsent(redisKey, 1, 10, TimeUnit.SECONDS);
        if(aBoolean) {
            LambdaQueryWrapper<ElectricFence> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ElectricFence::getId, req.getId());
            ElectricFence bd = this.getOne(queryWrapper);

            if (Objects.isNull(bd)) {
                throw new ServiceException("该电子围栏不存在");
            }

            LambdaQueryWrapper<ElectricFenceUser>  userLambdaQueryWrapper=new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(ElectricFenceUser::getUserId,req.getUserId());
            long count = this.electricFenceUserService.count(userLambdaQueryWrapper);


            ElectricFence electricFence = new ElectricFence();
            BeanUtils.copyProperties(req, electricFence);

            electricFence.setDelFlag("0");

            boolean update = this.updateById(electricFence);

            //更新负责人
            //在绑定表中能查到,是普通的修改操作
            if(count>0) {
                LambdaQueryWrapper<ElectricFenceUser> queryWrapper1 = new LambdaQueryWrapper<>();
                queryWrapper1.eq(ElectricFenceUser::getUserId, req.getUserId());
                ElectricFenceUser fenceUser = this.electricFenceUserService.getOne(queryWrapper1);
                fenceUser.setUserId(req.getUserId());
                fenceUser.setMobile(req.getMobile());
                this.electricFenceUserService.updateById(fenceUser);
                this.redisTemplate.delete(redisKey);
            }
            //查不到,是电子围栏启用操作
            else {
                ElectricFenceUser electricFenceUser = new ElectricFenceUser();
                electricFenceUser.setElectricId(electricFence.getId());
                electricFenceUser.setUserId(req.getUserId());
                electricFenceUser.setMobile(req.getMobile());
                this.electricFenceUserService.save(electricFenceUser);
            }
            //删掉
            this.redisTemplate.delete(redisKey);
            //更新已经绑定的设备
            this.updateRedisUtils.updateBingDevice();
            return update;
        }else {
            throw new ServiceException("用户已经被使用了，创建电子围栏失败");
        }
    }

    @Override
    public ElectricFenceResp findByid(Long id) {
        ElectricFenceResp resp=this.baseMapper.findById(id);
        return resp;
    }

    @Override
    public Boolean updateDel(Long[] ids) {
        for (Long id : ids) {
            ElectricFence db = this.getById(id);
            if(Objects.isNull(db)){
                throw new ServiceException("找不到数据");
            }
            db.setDelFlag("1");
            this.updateById(db);
            LambdaQueryWrapper<ElectricFenceUser> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(ElectricFenceUser::getElectricId,id);
            ElectricFenceUser fenceUser = this.electricFenceUserService.getOne(queryWrapper);
            //更新已经绑定的设备
            this.updateRedisUtils.updateBingDevice();
            this.electricFenceUserService.removeById(fenceUser);
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean editStatus(Long id) {
        String redisKey=RedisConstans.ELECTRIC_FENCE+id;
        Boolean aBoolean = this.redisTemplate.opsForValue().setIfAbsent(redisKey, 1, 1, TimeUnit.SECONDS);
        if(aBoolean) {
            LambdaQueryWrapper<ElectricFence> queryWrapper = new LambdaQueryWrapper();
            queryWrapper.eq(ElectricFence::getId, id);
            queryWrapper.eq(ElectricFence::getDelFlag, "0");
            ElectricFence db = this.getOne(queryWrapper);

            LambdaQueryWrapper<ElectricFenceUser> userLambdaQueryWrapper=new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(ElectricFenceUser::getElectricId,id);

            ElectricFenceUser user = this.electricFenceUserService.getOne(userLambdaQueryWrapper);

            if (Objects.isNull(db)) {
                throw new ServiceException("设备不存在");
            }
            //根据当前状态来修改
            if(db.getStatus().equals("0")){
                db.setStatus("1");
                this.electricFenceUserService.removeById(user);
            }else {
                db.setStatus("0");
            }
            //更新已经绑定的设备
            this.updateRedisUtils.updateBingDevice();

            this.redisTemplate.delete(redisKey);
            return this.updateById(db);
        }else {
            throw new ServiceException("设备状态已被修改");
        }
    }
}




